Vue Js Change Button Color and Icon on click:To change the button color and icon in Vue.js upon clicking, you can use conditional rendering and dynamic binding. Start by defining a data property to track the click state, such as “isClicked.” In the button element, use a conditional class binding to set the desired CSS class based on the “isClicked” value. Similarly, apply a conditional icon binding to display different icons based on the click state. Finally, use a click event handler to toggle the “isClicked” value, triggering the changes. With this setup, you can dynamically change the button color and icon in response to user clicks.
How can I change the button color and icon in Vue.js when it is clicked?
In the Below code snippet, Vue.js is used to change the color and icon of a button when it is clicked. The isActive
variable is a boolean data property in the Vue instance, initialized with a value of false
.
The button element has a :class
directive that applies the CSS class active
to it when isActive
is true
. This allows us to change the button’s color based on the state of isActive
.
Inside the button, there is an i
element representing an icon. The :class
directive on the i
element dynamically sets the CSS classes based on the value of isActive
. If isActive
is true
, the fa fa-check
class is applied, and if isActive
is false
, the fa fa-times
class is applied. This enables us to change the icon displayed on the button based on the button’s state.
Vue Js Change Button Color and Icon on click Example
<div id="app">
<button :class="{ 'active': isActive }" @click="isActive = !isActive">
<i :class="isActive ? 'fa fa-check' : 'fa fa-times'"></i>
</button>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
isActive: false
};
},
});
</script>